package com.u3k.app.mid.utils.net;

import android.util.Base64;
import com.u3k.app.mid.utils.statistics.StatisticsManager;
import com.u3k.mid.LogUtils;
import com.u3k.mid.ae;
import com.u3k.mid.ak;
import com.u3k.mid.at;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Random;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpCall extends HttpTask {
    public static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String str, SSLSession sSLSession) {
            return true;
        }
    };
    static final int MAX_RETRY_TIME = 3;
    static String TAG = "HttpCall";
    Callback callback;
    HttpClient client;
    Request request;

    public HttpCall(HttpClient httpClient, Request request, Callback callback) {
        this.client = httpClient;
        this.request = request;
        this.callback = callback;
    }

    private byte[] getBytesByInputStream(InputStream inputStream) {
        byte[] bArr = null;
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
        byte[] bArr2 = new byte[8192];
        while (true) {
            try {
                int read = bufferedInputStream.read(bArr2);
                if (read <= 0) {
                    break;
                }
                bufferedOutputStream.write(bArr2, 0, read);
            } catch (Exception e) {
                e.printStackTrace();
                StatisticsManager.getInstance().logException(ae.a(), e);
                try {
                    bufferedOutputStream.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
                try {
                    bufferedInputStream.close();
                } catch (IOException e22) {
                    e22.printStackTrace();
                }
            } catch (Throwable th) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e222) {
                    e222.printStackTrace();
                }
                try {
                    bufferedInputStream.close();
                } catch (IOException e2222) {
                    e2222.printStackTrace();
                }
                throw th;
            }
        }
        bufferedOutputStream.flush();
        bArr = byteArrayOutputStream.toByteArray();
        try {
            bufferedOutputStream.close();
        } catch (IOException e22222) {
            e22222.printStackTrace();
        }
        try {
            bufferedInputStream.close();
        } catch (IOException e222222) {
            e222222.printStackTrace();
        }
        return bArr;
    }

    private String getMIMEType(File file) {
        String toLowerCase = file.getName().toLowerCase();
        return toLowerCase.endsWith("png") ? "image/png" : (toLowerCase.endsWith("jpg") || toLowerCase.endsWith("jepg")) ? "image/jpg" : "application/octet-stream";
    }

    public static void trustAllHosts() {
        AnonymousClass2 anonymousClass2 = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] x509CertificateArr, String str) {
            }

            public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        try {
            SSLContext instance = SSLContext.getInstance("TLS");
            TrustManager[] trustManagerArr = new TrustManager[]{anonymousClass2};
            instance.init(null, trustManagerArr, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(instance.getSocketFactory());
        } catch (Exception e) {
            StatisticsManager.getInstance().logException(ae.a(), e);
            LogUtils.LogError(TAG, "trustAllHosts  Exception=", e);
        }
    }

    void addCustomHeader(HttpURLConnection httpURLConnection) {
        if (this.request.headers != null) {
            for (int i = 0; i < this.request.headers.size(); i += 2) {
                httpURLConnection.addRequestProperty((String) this.request.headers.get(i), (String) this.request.headers.get(i + 1));
            }
        }
    }

    void execute() {
        processRequest();
    }

    public String host() {
        return this.request.host();
    }

    Response processGet() {
        Exception exception;
        Throwable th;
        Response response = null;
        LogUtils.LogError(TAG, "processGet");
        Object obj = null;
        HttpURLConnection httpURLConnection = null;
        for (int i = 0; i < MAX_RETRY_TIME && r2 == null; i++) {
            try {
                LogUtils.LogError(TAG, "processGet.request.url:" + this.request.url);
                URL url = new URL(this.request.url);
                if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
                    trustAllHosts();
                    HttpURLConnection httpURLConnection2 = (HttpsURLConnection) url.openConnection();
                    httpURLConnection2.setHostnameVerifier(DO_NOT_VERIFY);
                    httpURLConnection = httpURLConnection2;
                } else {
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                }
                try {
                    httpURLConnection.setConnectTimeout(this.client.getConnectTimeout());
                    httpURLConnection.setReadTimeout(this.client.getReadTimeout());
                    httpURLConnection.setUseCaches(true);
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    httpURLConnection.addRequestProperty("Connection", "Keep-Alive");
                    addCustomHeader(httpURLConnection);
                    httpURLConnection.connect();
                    int responseCode = httpURLConnection.getResponseCode();
                    if (200 == responseCode) {
                        try {
                            response = new Response(responseCode, httpURLConnection.getHeaderFields(), getBytesByInputStream(httpURLConnection.getInputStream()));
                        } catch (Exception e) {
                            exception = e;
                            obj = 1;
                            try {
                                LogUtils.LogError(TAG, "processGet.Exception", exception);
                                response = new Response(0, null, null);
                                response.setErrorMsg(exception.getMessage());
                                StatisticsManager.getInstance().logException(ae.a(), exception);
                                if (httpURLConnection == null) {
                                    httpURLConnection.disconnect();
                                }
                            } catch (Throwable th2) {
                                th = th2;
                            }
                        } catch (Throwable th3) {
                            th = th3;
                        }
                    } else {
                        response = new Response(responseCode, null, null);
                    }
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                        obj = 1;
                    } else {
                        responseCode = 1;
                    }
                } catch (Exception e2) {
                    exception = e2;
                    LogUtils.LogError(TAG, "processGet.Exception", exception);
                    response = new Response(0, null, null);
                    response.setErrorMsg(exception.getMessage());
                    StatisticsManager.getInstance().logException(ae.a(), exception);
                    if (httpURLConnection == null) {
                        httpURLConnection.disconnect();
                    }
                } catch (Throwable th32) {
                    th = th32;
                }
            } catch (Exception e22) {
                exception = e22;
                LogUtils.LogError(TAG, "processGet.Exception", exception);
                response = new Response(0, null, null);
                response.setErrorMsg(exception.getMessage());
                StatisticsManager.getInstance().logException(ae.a(), exception);
                if (httpURLConnection == null) {
                    httpURLConnection.disconnect();
                }
            }
        }
        return response;
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        throw th;
    }

    Response processPostFile() {
        Response response;
        Exception exception;
        Throwable th;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(this.request.url);
            if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
                trustAllHosts();
                HttpURLConnection httpURLConnection2 = (HttpsURLConnection) url.openConnection();
                httpURLConnection2.setHostnameVerifier(DO_NOT_VERIFY);
                httpURLConnection = httpURLConnection2;
            } else {
                httpURLConnection = (HttpURLConnection) url.openConnection();
            }
            try {
                StringBuilder stringBuilder;
                httpURLConnection.setConnectTimeout(this.client.getConnectTimeout());
                httpURLConnection.setReadTimeout(this.client.getReadTimeout());
                httpURLConnection.setUseCaches(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                addCustomHeader(httpURLConnection);
                byte[] bArr = new byte[16];
                new Random().nextBytes(bArr);
                String encodeToString = Base64.encodeToString(bArr, 2);
                httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + encodeToString);
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
                OutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
                byte[] bytes = ("--" + encodeToString + "--\r\n").getBytes();
                if (this.request.files != null && this.request.files.size() > 0) {
                    for (Entry entry : this.request.files.entrySet()) {
                        File file = (File) entry.getValue();
                        String str = (String) entry.getKey();
                        stringBuilder = new StringBuilder();
                        stringBuilder.append("--");
                        stringBuilder.append(encodeToString);
                        stringBuilder.append("\r\n");
                        stringBuilder.append("Content-Disposition: form-data;name=\"" + str + "\";filename=\"" + file.getName() + "\"\r\n");
                        stringBuilder.append("Content-Type: " + getMIMEType(file) + "\r\n\r\n");
                        dataOutputStream.write(stringBuilder.toString().getBytes());
                        DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
                        bArr = new byte[1024];
                        while (true) {
                            int read = dataInputStream.read(bArr);
                            if (read == -1) {
                                break;
                            }
                            dataOutputStream.write(bArr, 0, read);
                        }
                        dataOutputStream.write("\r\n".getBytes());
                        dataInputStream.close();
                    }
                }
                if (!(this.request.bodyKeyValues == null || this.request.bodyKeyValues.isEmpty())) {
                    for (Entry entry2 : this.request.bodyKeyValues.entrySet()) {
                        stringBuilder = new StringBuilder();
                        stringBuilder.append("--");
                        stringBuilder.append(encodeToString);
                        stringBuilder.append("\r\n");
                        stringBuilder.append("Content-Disposition: form-data; name=\"" + ((String) entry2.getKey()) + "\"");
                        stringBuilder.append("\r\n");
                        stringBuilder.append("\r\n");
                        stringBuilder.append((String) entry2.getValue());
                        stringBuilder.append("\r\n");
                        dataOutputStream.write(stringBuilder.toString().getBytes());
                    }
                }
                dataOutputStream.write(bytes);
                dataOutputStream.flush();
                dataOutputStream.close();
                int responseCode = httpURLConnection.getResponseCode();
                if (200 == responseCode) {
                    response = new Response(responseCode, httpURLConnection.getHeaderFields(), getBytesByInputStream(httpURLConnection.getInputStream()));
                } else {
                    response = new Response(responseCode, null, null);
                }
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            } catch (Exception e) {
                exception = e;
            }
        } catch (Exception e2) {
            exception = e2;
            try {
                response = new Response(0, null, null);
                response.setErrorMsg(exception.getMessage());
                LogUtils.LogError(TAG, "processPostFile  Exception=" + exception.getMessage());
                StatisticsManager.getInstance().logException(ae.a(), exception);
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                return response;
            } catch (Throwable th2) {
                th = th2;
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                throw th;
            }
        } catch (Throwable th3) {
            th = th3;
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            throw th;
        }
        return response;
    }

    Response processPostText() {
        Exception exception;
        Throwable th;
        Response response = null;
        LogUtils.LogError(TAG, "processPostText");
        Object obj = null;
        HttpURLConnection httpURLConnection = null;
        for (int i = 0; i < MAX_RETRY_TIME && r2 == null; i++) {
            try {
                String header;
                int responseCode;
                URL url = new URL(this.request.url);
                if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
                    trustAllHosts();
                    HttpURLConnection httpURLConnection2 = (HttpsURLConnection) url.openConnection();
                    httpURLConnection2.setHostnameVerifier(DO_NOT_VERIFY);
                    httpURLConnection = httpURLConnection2;
                } else {
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                }
                try {
                    LogUtils.LogError(TAG, "processPostText   1");
                    httpURLConnection.setConnectTimeout(this.client.getConnectTimeout());
                    httpURLConnection.setReadTimeout(this.client.getReadTimeout());
                    httpURLConnection.setUseCaches(true);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    httpURLConnection.addRequestProperty("Connection", "Keep-Alive");
                    addCustomHeader(httpURLConnection);
                    LogUtils.LogError(TAG, "processPostText   2");
                    header = this.request.getHeader("Original-Encoding");
                    byte[] bytes = (header == null || !header.equals("1")) ? this.request.bodyText.getBytes() : at.a(this.request.bodyText);
                    LogUtils.LogError(TAG, "processPostText   3");
                    String header2 = this.request.getHeader("Original-Encrypt");
                    if (header2 != null && header2.equals("ab")) {
                        bytes = ak.a("xyzG7FBook9OverZ", bytes).getBytes();
                    }
                    LogUtils.LogError(TAG, "processPostText   4");
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(bytes);
                    outputStream.flush();
                    outputStream.close();
                    LogUtils.LogError(TAG, "processPostText   5");
                    responseCode = httpURLConnection.getResponseCode();
                } catch (Exception e) {
                    exception = e;
                    try {
                        response = new Response(0, null, null);
                        response.setErrorMsg(exception.getMessage());
                        LogUtils.LogError(TAG, "processPostText  Exception=", exception);
                        StatisticsManager.getInstance().logException(ae.a(), exception);
                        if (httpURLConnection == null) {
                            httpURLConnection.disconnect();
                        }
                    } catch (Throwable th2) {
                        th = th2;
                    }
                } catch (Throwable th3) {
                    th = th3;
                }
                try {
                    LogUtils.LogError(TAG, "processPostText   responseCode=" + responseCode);
                    if (200 == responseCode) {
                        Object headerField;
                        String a;
                        InputStream inputStream = httpURLConnection.getInputStream();
                        LogUtils.LogError(TAG, "processPostText   6");
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                        StringBuffer stringBuffer = new StringBuffer();
                        while (true) {
                            header = bufferedReader.readLine();
                            if (header == null) {
                                break;
                            }
                            stringBuffer.append(header);
                        }
                        LogUtils.LogError(TAG, "processPostText   7");
                        obj = "";
                        try {
                            obj = httpURLConnection.getHeaderField("Original-Encoding");
                            headerField = httpURLConnection.getHeaderField("Original-Encrypt");
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            headerField = "";
                        } catch (Throwable th32) {
                            th = th32;
                        }
                        LogUtils.LogError(TAG, "processPostText   8");
                        if ("ab".equals(headerField)) {
                            byte[] a2 = ak.a("xyzG7FBook9OverZ", stringBuffer.toString());
                            a = String.valueOf(1).equals(obj) ? at.a(a2) : new String(a2, "UTF-8");
                        } else {
                            a = stringBuffer.toString();
                        }
                        LogUtils.LogError(TAG, "processPostText   9");
                        response = new Response(responseCode, httpURLConnection.getHeaderFields(), a.getBytes());
                    } else {
                        response = new Response(responseCode, null, null);
                    }
                    int i2;
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                        i2 = 1;
                    } else {
                        i2 = 1;
                    }
                } catch (Exception e22) {
                    exception = e22;
                    obj = 1;
                    response = new Response(0, null, null);
                    response.setErrorMsg(exception.getMessage());
                    LogUtils.LogError(TAG, "processPostText  Exception=", exception);
                    StatisticsManager.getInstance().logException(ae.a(), exception);
                    if (httpURLConnection == null) {
                        httpURLConnection.disconnect();
                    }
                } catch (Throwable th322) {
                    th = th322;
                }
            } catch (Exception e222) {
                exception = e222;
                response = new Response(0, null, null);
                response.setErrorMsg(exception.getMessage());
                LogUtils.LogError(TAG, "processPostText  Exception=", exception);
                StatisticsManager.getInstance().logException(ae.a(), exception);
                if (httpURLConnection == null) {
                    httpURLConnection.disconnect();
                }
            }
        }
        return response;
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        throw th;
    }

    public Response processRequest() {
        LogUtils.LogError(TAG, "processRequest ");
        try {
            Response processGet;
            if (this.request.method.equals("GET")) {
                processGet = processGet();
            } else {
                if (this.request.method.equals("POST")) {
                    if (this.request.bodyText != null) {
                        processGet = processPostText();
                    } else if (this.request.files != null && this.request.files.size() > 0) {
                        processGet = processPostFile();
                    } else if (this.request.bodyKeyValues != null && this.request.bodyKeyValues.size() > 0) {
                        this.request.bodyText = this.request.bodyKeyValues();
                        processGet = processPostText();
                    }
                }
                processGet = null;
            }
            if (processGet == null || processGet.code != 200) {
                if (this.callback == null) {
                    return processGet;
                }
                this.callback.onFailure(processGet == null ? 0 : processGet.code, processGet == null ? null : processGet.getErrorMsg());
                return processGet;
            } else if (this.callback == null) {
                return processGet;
            } else {
                this.callback.onResponse(processGet);
                return processGet;
            }
        } catch (Exception e) {
            Exception exception = e;
            LogUtils.LogError(TAG, "error", exception);
            Response response = new Response(0, null, null);
            String message = exception != null ? exception.getMessage() : "";
            response.setErrorMsg(message);
            if (this.callback != null) {
                this.callback.onFailure(-1, message);
            }
            StatisticsManager.getInstance().logException(ae.a(), exception);
            return response;
        }
    }

    public final void run() {
        try {
            execute();
        } catch (Exception e) {
            if (this.callback != null) {
                this.callback.onFailure(-1, e.getMessage());
            }
            StatisticsManager.getInstance().logException(ae.a(), e);
        } finally {
            this.client.callFinished(this);
        }
    }

    public String streamToString(InputStream inputStream) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bArr = new byte[1024];
            while (true) {
                int read = inputStream.read(bArr);
                if (read != -1) {
                    byteArrayOutputStream.write(bArr, 0, read);
                } else {
                    byteArrayOutputStream.close();
                    inputStream.close();
                    return new String(byteArrayOutputStream.toByteArray());
                }
            }
        } catch (Exception e) {
            StatisticsManager.getInstance().logException(ae.a(), e);
            return null;
        }
    }
}
